package com.cloud.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloud.Enum.ConsumerTypeEnum;
import com.cloud.config.feign.ConsumerBridgeFeign;
import com.cloud.config.feign.ConsumerCommonFeign;
import com.cloud.service.LogSendFeignContain;
import com.cloud.util.JoyoungCloudHttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Conditional(JobConditionConfiguration.class)
@Slf4j
public class JoyoungSaveLogJob {

    @Autowired
    @Lazy
    ConsumerCommonFeign consumerCommonFeign;

    @Autowired
    @Lazy
    ConsumerBridgeFeign consumerBridgeFeign;

    @Autowired
    private LogSendFeignContain logSendFeignContain;

    //批量发送的条数
    @Value("${cloud.joyoung.log.consumer-size:50}")
    private Integer consumerSize;

    //时间间隔发送
    @Value("${cloud.joyoung.log.consumer-time:60000}")
    private Integer consumerTime;

    @Value("${cloud.joyoung.log.consumer-type:1}")
    private String consumerType;

    @Value("${cloud.joyoung.log.feign-url:https://gateway.joyoung.com/cloud-log-record-consumer/batchInsertLog}")
    private String url;

    @Value("${cloud.joyoung.log.token-url:https://gateway.joyoung.com/cloud-auth/app/token?appid=member&secret=wDNlTQ3}")
    private String tokenUrl;

    //准备发送的日志数组
    List sendlistTemp = null;

    String token = null;

    public String pullToken() {
        log.info("获取token定时任务执行");
        try {
            String result = JoyoungCloudHttpClientUtils.doPost(tokenUrl);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject != null) {
                String access_token = jsonObject.getString("access_token");
                token = access_token;
                return access_token;
            }
        } catch (Exception e) {
            log.error("获取token错误：" + e);
        }
        return null;
    }

    //每隔10秒执行一次
    @Scheduled(cron = "${cloud.joyoung.log.cron:*/10 * * * * ?}")
    public void execute() {

        synchronized (LogSendFeignContain.class) {

            if (sendlistTemp != null && sendlistTemp.size() > 1000) {
                sendlistTemp.clear();
                sendlistTemp = null;
                log.info("消息堆积太多，避免内存飙高");
            }

            //大于50条，或者时间超过几分钟，则进行同步
            if (logSendFeignContain.syslogs.size() >= consumerSize
                    || (System.currentTimeMillis() - logSendFeignContain.starTime > consumerTime)) {
                sendlistTemp = logSendFeignContain.syslogs;
                logSendFeignContain.syslogs = new ArrayList<>();
                logSendFeignContain.starTime = System.currentTimeMillis();
            }
        }

        if (!CollectionUtils.isEmpty(sendlistTemp)) {
            try {
                if (ConsumerTypeEnum.COMMON_FEIGN.getCode().equals(consumerType)) {

                    //普通feign调用
                    consumerCommonFeign.batchInsertLog(sendlistTemp);
                } else if (ConsumerTypeEnum.BRIDGE_FEIGN.getCode().equals(consumerType)) {

                    //bridge feign调用
                    consumerBridgeFeign.batchInsertLog(sendlistTemp);
                } else if (ConsumerTypeEnum.HTTPCLIENT.getCode().equals(consumerType)) {

                    if (StringUtils.isBlank(token)) {
                        //首先拉取一个token
                        this.pullToken();
                    }

                    Map headerMap = new HashMap<>();
                    headerMap.put("Authorization", token);

                    String result = JoyoungCloudHttpClientUtils.doPostJsonAddHeader(url, JSON.toJSONString(sendlistTemp), headerMap);
                    JSONObject jsonObject = JSONObject.parseObject(result);

                    // 获取到key为shoppingCartItemList的值
                    if (jsonObject.getString("message").contains("token已过期")) {

                        String tokens = this.pullToken();
                        headerMap.put("Authorization", tokens);

                        JoyoungCloudHttpClientUtils.doPostJsonAddHeader(url, JSON.toJSONString(sendlistTemp), headerMap);
                    }
                }
                sendlistTemp.clear();
                sendlistTemp = null;
            } catch (Exception e) {
                log.error("调用Feign接口发送日志错误：" + e);
            }
        }
    }
}
